<?php
declare(strict_types=1);

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 16:45:18
 * Info: 管理员管理
 */

namespace app\admin\controller;

use app\common\model\Admin as AdminModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\facade\View;
use think\response\View as ViewResponse;

class Admin extends Base
{

    /**
     * 管理员列表
     *
     * @return string|ViewResponse
     */
    public function index()
    {
        //获取角色组的名字和id
        $roleGroupName = AuthGroupModel::getRoleGroup();

        //判断是否是ajax发送方式
        if ($this->request->isAjax()) {
            $params = [
                'limit' => (int)$this->request->param('limit', 10),
                'page'  => (int)$this->request->param('page', 1),
                'field' => $this->request->param('field', 'id'),
                'order' => $this->request->param('order', 'asc'),
                'key'   => $this->request->param('key')
            ];

            $params['first'] = ($params['page'] - 1) * $params['limit'];

            $data = AdminModel::getAdminList($params);
            $this->success('ok', $data['list'], (int)$data['count']);
        }

        View::assign('role_group_name', $roleGroupName);

        return View::fetch();
    }

    /**
     * 添加管理员
     *
     * @return string|ViewResponse
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->input();

            // 验证必填字段
            $this->validateAddData($param);

            //判断用户名是否存在
            if (AdminModel::where('username', $param['username'])->count()) {
                $this->error(__('UsernameIsExist'));
            }

            // 处理密码
            $param['password'] = passwordHash($param['password']);

            // 处理状态
            if (isset($param['status']) && $param['status'] == 1) {
                $param['status'] = 'normal';
            }

            $authIds = $param['auth_ids'] ?? [];
            unset($param['auth_ids']);

            $param['create_time'] = time();
            $param['update_time'] = time();

            $adminId = AdminModel::strict(false)->insertGetId($param);

            //保存用户的角色组
            AuthGroupAccessModel::updateGroupAccess($adminId, $authIds);
            $this->success(__('OperationSuccess'));
        }

        $roleGroupName = AuthGroupModel::getRoleGroup();
        View::assign('role_group_name', $roleGroupName);

        return View::fetch();
    }

    /**
     * 编辑管理员
     *
     * @return string|ViewResponse
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            //获取序列化数据
            $param = $this->input();

            if (empty($param['id'])) {
                $this->error(__('ParamError'));
            }

            // 处理状态
            if (isset($param['status']) && $param['status'] == 1) {
                $param['status'] = 'normal';
            }

            //修改密码
            if ( ! empty($param['password'])) {
                $param['password'] = passwordHash($param['password']);
            } else {
                unset($param['password']);
            }

            $type = $param['type'] ?? '';
            //保存角色组，编辑个人信息的时候不处理用户组
            $authIds = $param['auth_ids'] ?? [];
            AuthGroupAccessModel::updateGroupAccess($param['id'], $authIds, $type);
            unset($param['auth_ids']);
            unset($param['type']);

            AdminModel::update($param, ['id' => $param['id']]);
            $this->success(__('OperationSuccess'));
        }

        $id              = $this->request->param('id');
        $roleGroupName   = AuthGroupModel::getRoleGroup();
        $data            = AdminModel::find($id);
        $authGroupAccess = AuthGroupAccessModel::where('uid', $id)->column('group_id');

        View::assign([
            'data'            => $data,
            'group_access'    => $authGroupAccess,
            'role_group_name' => $roleGroupName
        ]);

        return View::fetch();
    }

    /**
     * 删除管理员
     *
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function delete(): void
    {
        if ( ! $this->request->isAjax()) {
            $this->error(__('RequestMethodError'));
        }

        $id = (int)$this->request->param('id');

        if (empty($id)) {
            $this->error(__('ParamError'));
        }

        if ($id == 1) {
            $this->error(__('NotAllowedToDelAs1'));
        }

        AdminModel::where(['id' => $id])->delete();
        //删除角色组
        AuthGroupAccessModel::updateGroupAccess($id, []);

        $this->success(__('OperationSuccess'));
    }

    /**
     * 管理员列表页的按钮操作
     *
     * @return void
     */
    public function modify(): void
    {
        if ( ! $this->request->isAjax()) {
            $this->error(__('RequestMethodError'));
        }

        $id = (int)$this->request->param('id');

        if (empty($id)) {
            $this->error(__('ParamError'));
        }

        if ($id == 1) {
            $this->error(__('NotAllowedToModifyAs1'));
        }

        $field = $this->request->param('field');
        $val   = $this->request->param('val');

        if (isset($val) && $val == 1) {
            $val = 'normal';
        }

        AdminModel::update([$field => $val], ['id' => $id]);
        $this->success(__('OperationSuccess'));
    }

    /**
     * 获取基本资料
     *
     * @return string|ViewResponse
     */
    public function adminInfo()
    {
        $id   = (int)$this->request->param('id');
        $data = AdminModel::find($id);
        View::assign('data', $data);

        return View::fetch('user_info');
    }

    /**
     * 修改密码
     *
     * @return string|ViewResponse
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function adminPass()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();

            $rule = [
                'id|id'                          => 'require',
                'oldpwd|'.__('OldPassword')      => 'require',
                'newpwd|'.__('NewPassword')      => 'require',
                'confirm|'.__('ConfirmPassword') => 'require'
            ];

            $this->validate($param, $rule);

            if ($param['newpwd'] !== $param['confirm']) {
                $this->error(__('PasswordNotMatch'));
            }

            //查询旧密码是否正确
            $admin = AdminModel::where('id', $param['id'])->field('password')->find();
            if ( ! $admin) {
                $this->error(__('UserNotExist'));
            }

            if ( ! passwordVerify($param['oldpwd'], $admin['password'])) {
                $this->error(__('OldPasswordIsError'));
            }

            $data = [
                'password'    => passwordHash($param['newpwd']),
                'update_time' => time()
            ];

            AdminModel::update($data, ['id' => $param['id']]);
            $this->success(__('OperationSuccess'));
        }

        $id = cmf_get_admin_id();
        View::assign('id', $id);

        return View::fetch('user_pass');
    }

    /**
     * 验证添加管理员数据
     *
     * @param array $param
     *
     * @return void
     */
    private function validateAddData(array $param): void
    {
        if (empty($param['username'])) {
            $this->error(__('%s CantBeEmpty', [__('Username')]));
        }

        if (empty($param['password'])) {
            $this->error(__('%s CantBeEmpty', [__('Password')]));
        }

        if (empty($param['auth_ids'])) {
            $this->error(__('%s PleaseEnter', [__('RoleGroup')]));
        }
    }
}
